package org.jugile.web2;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Properties;

import org.jugile.util.Blob;
import org.jugile.util.Jugile;
import org.jugile.util.Vo;

public class Response implements Cloneable {
	public Response() { this.status = Cycle.HTTP_OK; }
	public Response( String status, String mimeType, InputStream data ) {
		this.status = status;
		this.mimeType = mimeType;
		this.data = data;
	}
	public Response( String status, String mimeType, String txt ) {
		this.status = status;
		this.mimeType = mimeType;
		this.data = new ByteArrayInputStream( txt.getBytes());
	}
	public Response(String mimeType, String txt) {
		this.mimeType = mimeType;
		this.data = new ByteArrayInputStream( txt.getBytes());
		this.status = Cycle.HTTP_OK;
	}
	public Response(Vo json) {
		String txt = "";
		if (json != null) txt = json.toJson();
		this.data = new ByteArrayInputStream( txt.getBytes());
		this.mimeType = Cycle.MIME_JSON;
		this.status = Cycle.HTTP_OK;
	}

	public void addHeader( String name, String value ) {
		header.put( name, value );
	}

	public String status;
	public String mimeType;
	public InputStream data;
	public Properties header = new Properties();

	private Blob bytes;
	
	protected void cache() {
		// write data into dataStr and close data input stream
		bytes = new Blob(data);
	}
	
	/**
	 * clone and prepare input stream.
	 */
	protected Response decache() {
		Response res = null;
		try {
			res = (Response)this.clone();
			res.data = new ByteArrayInputStream( bytes.getData());			
		} catch (Exception e) { Jugile.fail(e); }
		return res;
	}


	public String toString() {
		bytes = new Blob(data);
		return bytes.toString();
	}
	
}
